Display Selected value with Html.DropDownList in ASP.Net MVC

I wrote ToastManager about two months ago, and not try to covert it into ASP.Net. What ToastManager does is to collect people’s toast order for the morning toast run.

Why? I just think MVC is cool. It separate programming logic into 3 different layers nicely.

The first problem I encountered in writing MVC code was to find a way to display a dropdownlist with a selected value. It is funny. I feel like I am a complete novice when I use MVC.

Simply, you need to pass the selected value in creating SelectList. (from ASP.NET MVC Html.DropDownList SelectedValue)

for example,

    Slices = new SelectList(new int[] {1, 2, 3, 4}, 2);
[

The below is the code for my OrderFormViewModel class


public Models.Order Order { get; private set; }
public string[] Spread { get; private set; }
public SelectList Slices { get; private set; }

public OrderFormViewModel(Order order)
{
    Order = order;
    Spread = new[] { "Butter", "Jam", "Peanut Butter", "Bovril", "Honey", "Marmalade", "Marmite", "Vegemite" };
    int[] sliceList = new int[] {1, 2, 3, 4};
    Slices = new SelectList(sliceList, Order.Slice);
}

4 thoughts on “Display Selected value with Html.DropDownList in ASP.Net MVC

  1. //Simply, you need to pass the selected value in creating SelectList.

    => This is a non-sence. What if I lopp over a collection with 50 or so records and need to set different value for each of the DropDownLists. Your suggestion works just in basic scenario.

    => I cannot find how to solve this, your comment did not help. I think, as usually, it is better to skip Microsoft’s control and create my own :-(.

Leave a comment